package com.estun.backroundManagementService.modules.product.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.estun.backroundManagementService.config.properties.FtpProperties;
import com.estun.backroundManagementService.modules.product.model.ProductStationTime;
import com.estun.backroundManagementService.modules.product.service.ProductStationTimeService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;

@RestController
@Slf4j
@Api(tags = "ImageDownloadController", description = "产品视觉图片管理")
@RequestMapping("/product/imageDownload")

public class ImageDownloadController {

    @Autowired
    private FtpProperties ftpProperties;

    @Autowired
    private ProductStationTimeService productStationTimeService;

    @GetMapping("/downloadLatestImage")
    public String downloadLatestImage(@RequestParam Long productId, @RequestParam String stationId, @RequestParam String status) {
        String ftpHost = ftpProperties.getHosts().get(stationId);
        if (StringUtils.isBlank(ftpHost)) {
            return "未找到符合给定条件的主机";
        }
        FTPClient ftpClient = new FTPClient();
        try {

            ftpClient.connect(ftpHost);
            ftpClient.login(ftpProperties.getUsername(), ftpProperties.getPassword());
//            ftpClient.setSoTimeout(300000);
            int replyCode = ftpClient.getReplyCode();
            log.info("replyCode:{}", replyCode);
            ftpClient.setControlEncoding("utf-8");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            if (stationId.contains("OP060-1")) {
                String basePath1 = "/" + stationId + "/Front/" + status.toUpperCase() + "/" + datePath + "/";
                String imagePath1 = downloadAndSave(basePath1, ftpClient);
                String basePath2 = "/" + stationId + "/Side/" + status.toUpperCase() + "/" + datePath + "/";
                String imagePath2 = downloadAndSave(basePath2, ftpClient);
                updateStationRecord(productId, stationId, imagePath1 + ";" + imagePath2);

            } else {
                String basePath = "/" + stationId + "/" + status.toUpperCase() + "/" + datePath + "/";
                String imagePath = downloadAndSave(basePath, ftpClient);
                updateStationRecord(productId, stationId, imagePath);
            }

            return "图像下载成功";
        } catch (IOException e) {
            log.error("image down error :{}", JSON.toJSONString(e.getStackTrace()));
            return "下载图像失败: " + e.getMessage();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }
    }

    private String downloadAndSave(String basePath, FTPClient ftpClient) throws IOException {
        String latestImagePath = findLatestImagePath(ftpClient, basePath);
        if (latestImagePath != null) {
            String localBasePath = ftpProperties.getDownloadPath();
            saveImageLocally(localBasePath, latestImagePath, ftpClient);
            return Paths.get(localBasePath, latestImagePath.substring(1)).toString();
        } else {
            return "";
        }
    }


    private String findLatestImagePath(FTPClient ftpClient, String basePath) throws IOException {
        String currentPath = basePath;
        for (int depth = 0; depth < 2; depth++) {
            FTPFile[] files = ftpClient.listFiles(currentPath);

            FTPFile latestFolder = Arrays.stream(files)
                    .filter(FTPFile::isDirectory)
                    .max(Comparator.comparing(FTPFile::getTimestamp))
//                    .max((a, b) -> b.getName().compareTo(a.getName()))
                    .orElse(null);

            if (latestFolder != null) {
                currentPath += latestFolder.getName() + "/";
            } else {
                return null;
            }
        }

        FTPFile[] images = ftpClient.listFiles(currentPath);
//        FTPFile latestImage = Arrays.stream(images)
//                .filter(file -> !file.isDirectory()
////                        && file.getName().endsWith(".jpeg")
//                )
//                .max(Comparator.comparing(FTPFile::getTimestamp))
////                .max((a, b) -> b.getName().compareTo(a.getName()))
//                .orElse(null);
        // 按照文件名中的时间部分构建比较器来确定最新图片
        FTPFile latestImage = Arrays.stream(images)
                .filter(file ->!file.isDirectory())
                .max(Comparator.comparing(this::extractImageNumber))
                .orElse(null);

        return latestImage!= null? currentPath + latestImage.getName() : null;
    }

    private Integer extractImageNumber(FTPFile file) {
        // 假设文件名格式为 "XXXXX_XXX_OK_YYYYMMDD_HHMMSS"
        String name = file.getName();
        // 提取文件名中的数字序列，这里假设数字序列是文件名的第一部分，如 "00420"
        String numberPart = name.split("_")[0];
        return Integer.parseInt(numberPart);
    }
    private void saveImageLocally(String localBasePath, String ftpImagePath, FTPClient ftpClient) throws IOException {
        Path localFullPath = Paths.get(localBasePath, ftpImagePath.substring(1)); // Remove the leading '/'
        Files.createDirectories(localFullPath.getParent()); // 创建父目录

        try (OutputStream outputStream = new FileOutputStream(localFullPath.toFile())) {
            if (!ftpClient.retrieveFile(ftpImagePath, outputStream)) {
                throw new IOException("下载图像失败: " + ftpImagePath);
            }
        }
    }


    private void updateStationRecord(Long productId, String stationId, String imagePath) {
        ProductStationTime productStationTime = productStationTimeService.getByProductIdAndStationId(productId, stationId);

        if (productStationTime != null && productStationTime.getId() != null && StringUtils.isNotBlank(imagePath)) {
            log.info("imagePath:{}，id:{}", imagePath, productStationTime.getId());
            ProductStationTime stationTime = new ProductStationTime();
            stationTime.setId(productStationTime.getId());
            stationTime.setImagePath(imagePath);

            // 创建一个 Wrapper 对象，用于更新指定字段
            UpdateWrapper<ProductStationTime> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("image_path", imagePath).eq("id", productStationTime.getId());

            // 更新数据库记录，只更新 imagePath 字段
            productStationTimeService.update(updateWrapper);
        }



    }


}
